import { useMemo, useState, useEffect, Key, useRef } from 'react';
import { Modal, message, Button, Table, Input, Tree, Spin } from 'antd';
import Pagination from '@inbiz/basic/Pagination';
import { InbizIcon } from '@inbiz/utils';
import { getMessageGroup, getMessageByGroupKey } from '../../server';
import './style.less';
const { DirectoryTree } = Tree;

export default function MessageTemp(props: any) {
    const { modalParams, value, onChange } = props;
    const [groupLoading, setGroupLoading] = useState(false);
    const [templateLoading, setTemplateLoading] = useState(false);
    const [groupData, setGroupData] = useState<any[]>([]);
    const [templateData, setTemplateData] = useState<any[]>([]);
    const [groupSelectedKeys, setGroupSelectedKeys] = useState<Key[]>([]);
    const [tempSelectedKeys, setTempSelectedKeys] = useState<Key[]>(value ? [value?.key] : []);
    const [tempSelected, setTempSelected] = useState<any[]>(value ? [value] : []);
    const [selectedAppId, setSelectedAppId] = useState<string>('');
    const [searchValue, setSearchValue] = useState<string>('');
    const [pageParam, setPageParam] = useState({ PageIndex: 1, PageSize: 10, total: 0 });

    const noticemodeFormat = (array: Array<any>) => {
        array = array?.map((item) => {
            switch (item) {
                case 1:
                    return '企业微信';
                case 2:
                    return '钉钉';
                case 3:
                    return '邮件';
                case 4:
                    return '短信';
                case 5:
                    return 'web端/移动端';
                case 6:
                    return 'WebHook';
                default:
                    return item;
            };
        });
        return array?.join(',');
    };

    const columns = useMemo(() => {
        return [
            {
                title: '模板名称',
                dataIndex: 'Name',
                key: 'Name',
                ellipsis: true,
            },
            {
                title: '推送至',
                dataIndex: 'Noticemode',
                key: 'Noticemode',
                ellipsis: true,
                render: (t: string) => noticemodeFormat(JSON.parse(t)),
            },
        ]
    }, []);

    const onSearch = () => {
        getTemplateData(groupSelectedKeys?.[0], selectedAppId, { PageIndex: 1, PageSize: 10 }, searchValue);
    };

    const onCancel = () => {
        modalParams?.onCancel && modalParams?.onCancel();
    };

    const onOk = () => {
        onChange({ key: tempSelected?.[0]?.Key, name: tempSelected?.[0]?.Name, appId: tempSelected?.[0]?.AppId });
        modalParams?.onCancel && modalParams?.onCancel();
    };

    const onSelect = (selectedKeys: Key[], e: { event: "select"; selected: boolean; node: any; selectedNodes: any[]; nativeEvent: MouseEvent; }) => {
        setSearchValue('');
        if (e?.node?.children) {
            return;
        };
        setGroupSelectedKeys(selectedKeys);
        getTemplateData(selectedKeys?.[0], e?.node?.appId, { PageIndex: 1, PageSize: 10 });
    };

    const onPageChange = ({ current, pageSize }: { current: number, pageSize: number }) => {
        getTemplateData(groupSelectedKeys?.[0], selectedAppId, { PageIndex: current, PageSize: pageSize }, searchValue);
    };

    const getTemplateData = async (key: Key, appId: string, pageData?: { PageIndex: number, PageSize: number }, searchValue?: string) => {
        setTemplateLoading(true);
        setSelectedAppId(appId);
        try {
            let results = await getMessageByGroupKey({ GroupKey: key, appId, PageIndex: pageData?.PageIndex || pageParam?.PageIndex, PageSize: pageData?.PageSize || pageParam?.PageSize, TemplateName: searchValue });
            setPageParam({
                PageIndex: pageData?.PageIndex || pageParam?.PageIndex,
                PageSize: pageData?.PageSize || pageParam?.PageSize,
                total: results?.TotalCount,
            });
            setTemplateData(results?.Items);
            setTemplateLoading(false);
        } catch (error: any) {
            setTemplateLoading(false);
            message.error(error);
        };
    };

    const getMessageGroups = async () => {
        setGroupLoading(true);
        try {
            let results = await getMessageGroup();
            if (results && results?.length) {
                results = results?.map((item: any) => {
                    return {
                        title: item?.DisplayName,
                        key: item?.AppId,
                        children: item?.Children?.map((item1: any) => {
                            return {
                                title: item1?.GroupName,
                                key: item1?.GroupKey,
                                appId: item?.AppId,
                            }
                        })
                    }
                });
                setGroupData(results);
                if (results?.[0]?.children?.[0]?.key) {
                    setGroupSelectedKeys([results?.[0]?.children?.[0]?.key]);
                    await getTemplateData(results?.[0]?.children?.[0]?.key, results?.[0]?.key);
                };
            };
            setGroupLoading(false);
        } catch (error: any) {
            setGroupLoading(false);
            message.error(error);
        };
    };

    useEffect(() => {
        getMessageGroups();
    }, []);

    return (
        <Modal
            {...modalParams}
            title='消息模板'
            bodyStyle={{
                height: 450,
                padding: '10px 20px 20px 20px',
            }}
        >
            <div className='process-designer-message-temp-body'>
                <div className='process-designer-message-temp-left'>
                    <Spin spinning={groupLoading}>
                        {
                            groupData?.length
                            &&
                            <DirectoryTree
                                onSelect={onSelect}
                                treeData={groupData}
                                icon={null}
                                defaultExpandedKeys={[groupData?.[0]?.key || '']}
                                selectedKeys={groupSelectedKeys}
                                switcherIcon={
                                    <InbizIcon
                                        type={'icon-ic-show_more'}
                                        style={{
                                            fontSize: 14,
                                            position: 'relative',
                                            color: '#aaa',
                                            top: '1px',
                                            right: '-2px',
                                        }}
                                    />
                                }
                            />
                        }
                    </Spin>
                </div>
                <div className='process-designer-message-temp-right'>
                    <div className='process-designer-message-temp-search'>
                        <Input
                            placeholder={'请输入消息模板名称'}
                            style={{ marginRight: 20, width: 260 }}
                            suffix={
                                <InbizIcon
                                    type="icon-ic-sousuo"
                                    style={{ fontSize: '15px', color: '#d9d9d9' }}
                                    onClick={onSearch}
                                />
                            }
                            onPressEnter={onSearch}
                            value={searchValue}
                            onChange={(e) => { setSearchValue(e?.target?.value) }}
                        />
                    </div>
                    <Table
                        loading={templateLoading}
                        columns={columns}
                        dataSource={templateData}
                        size='small'
                        pagination={false}
                        scroll={{
                            y: 240
                        }}
                        rowKey={'Key'}
                        rowSelection={{
                            type: 'radio',
                            selectedRowKeys: tempSelectedKeys,
                            onChange: (selectedRowKeys, selectedRows) => {
                                setTempSelectedKeys(selectedRowKeys);
                                setTempSelected(selectedRows);
                            },
                        }}
                        onRow={(r) => {
                            return {
                                onClick: () => {
                                    setTempSelectedKeys([r?.Key]);
                                    setTempSelected([r]);
                                }
                            }
                        }}
                    />
                    <Pagination
                        size="small"
                        options={[10, 20, 30, 40, 50]}
                        total={pageParam?.total}
                        current={pageParam?.PageIndex}
                        pageSize={pageParam?.PageSize}
                        onChange={onPageChange}
                    />
                </div>
            </div>
            <div className='process-designer-message-temp-footer'>
                <Button type='primary' onClick={onOk}>确定</Button>
                <Button onClick={onCancel}>取消</Button>
            </div>
        </Modal>
    );
};